import React from 'react';
import { Link } from 'react-router-dom';

import User from 'service/user-service.jsx';
import MUtil from 'util/mm.jsx';

const _user = new User();
const _mm = new MUtil();

class NavTop extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            //username: 从本地存储获取数据
            username: _mm.getStorage('userInfo').username
        }
    }

    navToLoginPage(e) {
        window.location.href='/login';
    }
    //退出登录
    onLogout() {
        _user.logout().then(res => {
            _mm.removeStorage('userInfo');
            window.location.href='/login'
        },errMsg => {
            _mm.errorTips(errMsg);
        } )
    }
    render() {
        return (
            <div className="navbar navbar-default top-navbar">
                <div className="navbar-header">
                    <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse">
                        <span className="sr-only">Toggle navigation</span>
                        <span className="icon-bar"></span>
                        <span className="icon-bar"></span>
                        <span className="icon-bar"></span>
                    </button>
                    <Link className="navbar-brand" to="/"><b>Space</b>Mall</Link>
                </div>

                <ul className="nav navbar-top-links navbar-right">
                    <li className="dropdown">
                        <a className="dropdown-toggle" href="javascript:;">
                            <i className="fa fa-user fa-fw"></i>
                            {
                                this.state.username ? <span>欢迎管理员 ： {this.state.username}</span> : <span onClick={e=> this.navToLoginPage(e)}>您好！请登录</span>
                            }
                            {
                                this.state.username ? <i className="fa fa-caret-down"></i> : null
                            }
                        </a>

                        {
                            this.state.username ? 
                            <ul className="dropdown-menu dropdown-user">
                            <li>
                                <a onClick={() => { this.onLogout() }}>
                                    <i className="fa fa-sign-out fa-fw"></i>
                                    <span>退出登录</span>
                                </a>
                            </li>
                        </ul>

                          : null
                        }
                    </li>

                </ul>
            </div>
        );
    }
}

export default NavTop